import React from "react";
import { Button, Form, Input, message, Select } from "antd";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { signIn, createUser, searchUsersName } from "../../untils/api";
import { useHistory } from "react-router-dom";
import { useState } from "react";
import "./index.scss";
const { Option } = Select;

function Register(props) {
  const [canRegister, setCanRegister] = useState({});
  var history = useHistory();
  const onFinish = (values) => {
    createUser(values).then((res) => {
      if (res.data.code === 200) {
        signIn(values).then((res) => {
          if (res.data.code == 200) {
            localStorage.setItem("userInfo", JSON.stringify(res.data.userInfo));
            localStorage.setItem("token", res.data.token);
            history.push("index/home");
            message.success(res.data.msg);
          } else {
            message.error(res.data.msg);
          }
        });
      }
    });
  };

  const iptBlur = (e) => {
    searchUsersName({ userName: e.target.value }).then((res) => {
      setCanRegister(res.data);
    });
  };

  return (
    <div className="register">
      <Form
        style={{ background: "transparent" }}
        name="normal_login"
        className="register-form"
        initialValues={{ remember: true }}
        onFinish={onFinish}
      >
        <Form.Item
          name="userName"
          rules={[{ required: true, message: "Please input your Username!" }]}
        >
          <Input
            onBlur={iptBlur}
            prefix={<UserOutlined className="site-form-item-icon" />}
            placeholder="请输入用户名"
            style={{ outline: "none", borderRadius: "20px" }}
          />
        </Form.Item>
        <span
          className={`msgBox ${canRegister.code !== 200 ? "red" : "green"}`}
        >
          {canRegister?.msg}
        </span>
        <Form.Item
          name="userPass"
          rules={[{ required: true, message: "Please input your Password!" }]}
        >
          <Input
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            placeholder="请输入密码"
            style={{ outline: "none", borderRadius: "20px" }}
          />
        </Form.Item>
        <Form.Item>
          <Button
            disabled={canRegister.code !== 200}
            type="primary"
            htmlType="submit"
            className="register-form-button"
          >
            注册
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}

export default Register;
